package com.example.uniappspringbootstartweb.service;

import com.example.uniappspringbootstartweb.DTO.UserDTO;
import com.example.uniappspringbootstartweb.entity.User;
import com.example.uniappspringbootstartweb.mapper.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Optional;

/**
 * Created by lilijava
 * on 2024/12/28
 * <p>
 * on  uni-app-springboot-start-web
 */
@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    public User findById( Long id) {
        return userRepository.findAllById(id);
    }

    public User registerUser(UserDTO userDTO) {
        if (userRepository.existsByUsername(userDTO.getUsername())) {
            throw new RuntimeException("U,sername already exists");
        }
        User newUser = new User();
        newUser.setUsername(userDTO.getUsername());
        newUser.setPassword(userDTO.getPassword()); // 直接保存明文密码
        newUser.setImg("/static/img/003.jpg");
        newUser.setNichen("新用户");
        newUser.setCreatedAt(LocalDateTime.now());
        return userRepository.save(newUser);
    }
    public User authenticateUser(UserDTO userDTO) {
        Optional<User> optionalUser = userRepository.findByUsername(userDTO.getUsername());
        if (!optionalUser.isPresent() || !userDTO.getPassword().equals(optionalUser.get().getPassword())) {
            throw new RuntimeException("Invalid username or password");
        }
        return optionalUser.get();
    }
    public User findUserByUsername(UserDTO userDTO) {
        Optional<User> optionalUser = userRepository.findByUsername(userDTO.getUsername());
        if (!optionalUser.isPresent() || !userDTO.getPassword().equals(optionalUser.get().getPassword())) {
            throw new RuntimeException("Invalid username or password");
        }
        return optionalUser.get();
    }
}
